<template>
  <div class="section-create-edit">
    <el-form label-position="right" label-width="80px">
      <el-form-item label="课程名称">
        <el-input v-model="courseName" disabled></el-input>
      </el-form-item>
      <el-form-item label="章节名称" >
        <el-input v-model="sectionForm.sectionName"></el-input>
      </el-form-item>
      <el-form-item label="章节描述">
        <el-input type="textarea" :rows="2" style="width: 100%" v-model="sectionForm.description"></el-input>
      </el-form-item>
      <el-form-item label="章节排序">
        <el-input type="Number" v-model="sectionForm.orderNum">
          <template slot="append">数字控制排序，数字越大越靠后</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getCourseById } from '@/services/course'
import { saveOrUpdateSection, getBySectionId } from '@/services/course-section'

export default {
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    courseId: {
      type: [Number, String]
    },
    sectionId: {
      type: [Number, String]
    }
  },
  name: 'SectionCreateEdit',
  data () {
    return {
      dialogVisible: true,
      sectionForm: {
        sectionName: '',
        courseId: this.courseId,
        description: '',
        orderNum: 0
      },
      courseName: ''
    }
  },
  created () {
    // 加载课程名
    this.loadCourseName()
    // 加载章节信息
    this.loadSectionInfo()
  },
  methods: {
    async loadSectionInfo () {
      const { data } = await getBySectionId(this.sectionId)
      if (data.code === '000000') {
        this.sectionForm = data.data
      }
    },
    async loadCourseName () {
      const { data } = await getCourseById(this.courseId)
      if (data.code === '000000') {
        this.courseName = data.data.courseName
      }
    },
    async onSubmit () {
      console.log(this.sectionForm)
      const { data } = await saveOrUpdateSection(this.sectionForm)
      if (data.code === '000000') {
        this.$message.success(`${this.isEdit ? '编辑' : '添加'}成功`)
        // 关闭提示框(需要子组件向父组件传递状态)
        this.$emit('success')
      }
    },
    onCancel () {
      // 设置取消状态，让父组件处理
      this.$emit('cancel')
      this.sectionForm = {}
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-form {
    width: 90%;
    margin: 0 auto;
  }
</style>
